﻿CREATE FUNCTION [dbo].[fn_PrimaryKeyColumns]
(
	@Table sysname
)
RETURNS TABLE
AS
	RETURN (
	    SELECT c.[name] AS ColumnName
	    FROM   sys.tables t
	           INNER JOIN sys.key_constraints kc
	                ON  kc.parent_object_id = t.[object_id]
	           INNER JOIN sys.indexes i
	                ON  kc.unique_index_id = i.index_id
						AND i.[object_id] = kc.parent_object_id
	           INNER JOIN sys.index_columns ic
	                ON  ic.[object_id] = i.[object_id]
						AND ic.index_id = i.index_id
	           INNER JOIN sys.columns c
	                ON  c.[object_id] = ic.[object_id]
						AND c.column_id = ic.column_id
	    WHERE  t.[type] = 'U'
	           AND t.[name] = @Table
		       AND t.[type] = 'U'
	           AND kc.[type] = 'PK'
	           AND i.is_primary_key = 1
	)